package com.upf1sh.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class ThingsboardTelemetry {
    public static void main(String[] args) throws IOException {
        // Thingsboard API URL
        String apiUrl = "http://106.12.118.231:1088/api/plugins/telemetry/DEVICE/468b2870-4872-11ed-acbc-d3a2ec121048/values/timeseries";

        // Your device's entityType and entityId
        String entityType = "devices";
        String entityId = "25066400-5b3a-11ed-bb54-b94cc16f5dd5";

        // Your access token
        String accessToken = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI3MTAzMjA1MzRAcXEuY29tIiwic2NvcGVzIjpbIlRFTkFOVF9BRE1JTiJdLCJ1c2VySWQiOiIyYjM0Zjc5MC1mMzU2LTExZWEtODAyNy02M2ZjMjA5MzIzMzAiLCJlbmFibGVkIjp0cnVlLCJpc1B1YmxpYyI6ZmFsc2UsInRlbmFudElkIjoiMWQ5ZDBjMzAtZjM1Ni0xMWVhLTgwMjctNjNmYzIwOTMyMzMwIiwiY3VzdG9tZXJJZCI6IjEzODE0MDAwLTFkZDItMTFiMi04MDgwLTgwODA4MDgwODA4MCIsImlzcyI6InRoaW5nc2JvYXJkLmlvIiwiaWF0IjoxNjg5MTQwMzQ3LCJleHAiOjE2ODkxNDkzNDd9.NR_Pjr0gBOMnz0tIDWdFyfEsk1fV4eJa8jhmLaFkbHvC_rJMfrZ98NM_Qi_T8Uft8fDeWuhyARWUA1SDQQ_NWQ";

        // Create the URL object
        String endpointUrl = apiUrl.replace("{entityType}", entityType).replace("{entityId}", entityId);
        URL url = new URL(endpointUrl);

        // Create an HTTP client
        CloseableHttpClient client = HttpClients.createDefault();

        // Create an HTTP GET request with authorization header
        HttpGet request = new HttpGet(url.toString());
        request.addHeader("X-Authorization", "Bearer " + accessToken);

        // Send the GET request
        HttpResponse response = client.execute(request);

        // Get the response code
        int responseCode = response.getStatusLine().getStatusCode();

        // If the response code indicates success
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // Read the response payload
            HttpEntity entity = response.getEntity();
            String responseBody = EntityUtils.toString(entity);
            // Print the received telemetry data
            System.out.println("Telemetry Data: " + responseBody);
        } else {
            // Print the error response
            System.out.println("Error response: " + response.getStatusLine().getReasonPhrase());
        }

        // Close the HttpClient
        client.close();
    }
}